<?php

namespace app\controller;

use think\Request;
use app\model\SystemConfig;
use Exception;

class System
{
    /**
     * 获取图标库
     */
    public function getIcons(Request $request)
    {
        try {
            $category = $request->param('category');

            $query = \app\model\Icon::where('is_active', 1);

            if ($category) {
                $query->where('category', $category);
            }

            $icons = $query->order('sort', 'asc')
                ->order('id', 'asc')
                ->select();

            return success($icons, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取加密方式列表
     */
    public function getEncryptMethods(Request $request)
    {
        try {
            $methods = SystemConfig::getEncryptMethods();

            // 确保返回数组
            if (!is_array($methods)) {
                $methods = ['AES-256-GCM', 'AES-256-CBC', 'AES-128-GCM', '3DES', 'SM4'];
            }

            $result = [];
            foreach ($methods as $method) {
                $result[] = [
                    'value' => $method,
                    'label' => $this->getEncryptMethodLabel($method),
                    'description' => $this->getEncryptMethodDescription($method),
                ];
            }

            return success($result, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取公开配置
     */
    public function getPublicConfig(Request $request)
    {
        try {
            $config = SystemConfig::getPublicConfigs();

            return success($config, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 版本检查
     */
    public function checkVersion(Request $request)
    {
        try {
            $currentVersion = $request->param('version');
            $platform = $request->param('platform');

            $latestVersion = SystemConfig::get('app_version', '1.0.0');

            $result = [
                'current_version' => $currentVersion,
                'latest_version' => $latestVersion,
                'has_update' => version_compare($currentVersion, $latestVersion, '<'),
                'update_info' => [
                    'title' => '发现新版本',
                    'description' => '修复已知问题，优化用户体验',
                    'force_update' => false,
                    'download_url' => '',
                ],
            ];

            return success($result, '检查完成');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 用户反馈
     */
    public function feedback(Request $request)
    {
        try {
            $userId = $request->userId ?? null; // 可能未登录
            $type = $request->param('type');
            $content = $request->param('content');
            $contact = $request->param('contact');
            $deviceInfo = $request->param('device_info', []);

            if (empty($type) || empty($content)) {
                return error('反馈类型和内容不能为空');
            }

            // 这里可以保存到数据库或发送邮件
            $feedbackData = [
                'user_id' => $userId,
                'type' => $type,
                'content' => $content,
                'contact' => $contact,
                'device_info' => json_encode($deviceInfo),
                'ip' => $request->ip(),
                'user_agent' => $request->header('user-agent'),
                'created_at' => date('Y-m-d H:i:s'),
            ];

            // TODO: 保存反馈数据到数据库

            // 记录日志
            if ($userId) {
                \app\model\UserLog::record($userId, 'feedback', "提交反馈: {$type}");
            }

            return success(null, '反馈提交成功，谢谢您的建议');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取应用信息
     */
    public function getAppInfo(Request $request)
    {
        try {
            $info = [
                'app_name' => SystemConfig::get('app_name', '账号密码管理器'),
                'app_version' => SystemConfig::get('app_version', '1.0.0'),
                'company' => '账号管理团队',
                'website' => 'https://www.accountmanage.com',
                'email' => 'support@accountmanage.com',
                'privacy_url' => 'https://www.accountmanage.com/privacy',
                'terms_url' => 'https://www.accountmanage.com/terms',
                'features' => [
                    '多平台支持',
                    '端到端加密',
                    '云端同步',
                    '生物识别',
                    '密码生成器',
                    '密码强度检测',
                ],
            ];

            return success($info, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 健康检查
     */
    public function health(Request $request)
    {
        try {
            $health = [
                'status' => 'ok',
                'timestamp' => time(),
                'version' => SystemConfig::get('app_version', '1.0.0'),
                'database' => 'connected',
                'cache' => 'connected',
            ];

            return success($health, '系统正常');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取加密方式标签
     */
    private function getEncryptMethodLabel($method)
    {
        $labels = [
            'AES-256-GCM' => 'AES-256-GCM（推荐）',
            'AES-256-CBC' => 'AES-256-CBC',
            'AES-128-GCM' => 'AES-128-GCM',
            '3DES' => '3DES（兼容）',
            'SM4' => 'SM4（国密）',
        ];

        return $labels[$method] ?? $method;
    }

    /**
     * 获取加密方式描述
     */
    private function getEncryptMethodDescription($method)
    {
        $descriptions = [
            'AES-256-GCM' => '安全性最高，推荐使用',
            'AES-256-CBC' => '兼容性好，安全性高',
            'AES-128-GCM' => '性能较好，安全性高',
            '3DES' => '兼容老设备，安全性一般',
            'SM4' => '国密算法，符合国产化要求',
        ];

        return $descriptions[$method] ?? '';
    }
}